import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

export const pureAxios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api base_url
  timeout: 5000 // 请求超时时间
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = getToken()
    if (error.response.status === 403) {
      Message({
        message: 'Forbidden',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      Message({
        message: 'Unauthorized',
        type: 'error',
        duration: 5 * 1000
      })
      if (token) {
        store.dispatch('user/logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    } else {
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
  }
  return Promise.reject(error)
}

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  err
)
pureAxios.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  err
)

// response interceptor
service.interceptors.response.use(
  response => {
    return response.data
  },
  err
)

export {
  service as request
}
